package com.zr.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zr.dao.InsertteaDao;
import com.zr.daoImpl.InsertteaDaoImplljc;
import com.zr.model.Teacher;
import com.zr.service.InsertteaServiceljc;
import com.zr.serviceImpl.InsertteaServiceImplljc;
import com.zr.util.JDBCUtil;

public class InsertteaControllerljc extends HttpServlet{
	
	//新增教师控制器
	InsertteaServiceljc inserts = new InsertteaServiceImplljc();
	InsertteaDao insert = new InsertteaDaoImplljc();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf8");
		resp.setCharacterEncoding("utf8");
		PrintWriter pw = resp.getWriter();
		boolean flag = true;
		String uname = req.getParameter("uname");//获取用户名
		String upsw = req.getParameter("upsw"); //密码
		String tname = req.getParameter("tname");//教师名
		String tage = req.getParameter("tage");//年龄
		String tsex = req.getParameter("tsex");//性别
		String address = req.getParameter("address");//家庭住址
		String tpnumber = req.getParameter("tpnumber");	//电话号码
		int rid = 2;
		Connection con = JDBCUtil.getConnection();
		try {
			con.setAutoCommit(false);
			//在teacher表中新增教师
			insert.insertteacher(tname, tage, tsex, address, tpnumber, con);
			//在user表中新增用户
			insert.insertUser(uname, upsw, rid, con);
			con.commit();	//手动提交
		} catch (SQLException e) {
			try {
				con.rollback();
				flag = false;  //判断是否回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		int uid = insert.findUidByUnameAndUpsw(uname, upsw).getUid();//获取刚创建的uid
		int tid = insert.findTidBytnameAndSex(tname, tsex).getTid();//获取刚创建的tid
		boolean f = insert.updateTidFromUser(tid, uid);//调用方法设置user表中的tid
		if(flag){
			pw.write("1");
			if(f){				
			}else{
				pw.write("3");
			}
		}else{
			pw.write("0");
		}
		pw.flush();
		pw.close();
	}
}
